#!/bin/bash

LEVEL=$1
shift
CC_FOLDER=cppcheck_report
CC_FILELIST=$CC_FOLDER/.tmp_ccheck_files.txt
CC_RESULT=$CC_FOLDER/.tmp_ccheck_report.txt
CC_SUPRESS="`dirname "$0"`/plugin-cppcheck-supress.txt"
CC_FOLDERS="`dirname "$0"`/plugin-cppcheck-folders.txt"

mkdir -p ${CC_FOLDER}

# assumption: /usr/bin/cppcheck is 2.6 while /usr/local/bin/cppcheck is 1.8.4
CPPCHECK_CMD="cppcheck"
if [[ -f "/usr/bin/cppcheck" ]]; then
    CPPCHECK_CMD="/usr/bin/cppcheck"
fi

# check cpuinfo if JOB_NUM was not set.
if [[ -z $JOB_NUM && -e "/proc/cpuinfo" ]]; then
    JOB_NUM=`cat /proc/cpuinfo | grep -c 'processor'`
fi
if [[ $JOB_NUM -lt 1 ]]; then
    JOB_NUM=1
fi
if [[ $JOB_NUM -gt 8 ]]; then
    JOB_NUM=8
fi
echo "JOB_NUM = ${JOB_NUM} ..."

cmd_line="$CPPCHECK_CMD -j ${JOB_NUM} --error-exitcode=44"
cmd_line="$cmd_line --inline-suppr"
cmd_line="$cmd_line --xml"
cmd_line="$cmd_line --language=c++"
cmd_line="$cmd_line --enable=${LEVEL} --output-file=${CC_RESULT}"

# 命令行指定了目标目录
if [[ ! -z $1 ]]; then
    find $* \( -name '*.c' -o -name '*.cpp' -o -name '*.h' \) > ${CC_FILELIST}
    cmd_line="$cmd_line --file-list=${CC_FILELIST}"
# 按文件中指定的prj文件检查
elif [[ -f $CPPCHECK_PROJECT ]]; then
    cmd_line="$cmd_line --project=$CPPCHECK_PROJECT"
elif [[ -f $CC_FOLDERS ]]; then
    folder_list=""
    while read -r line; do
        if [[ $line != \#* ]] && [[ ! -z $line ]] ; then
            folder_list="$folder_list $line"
        fi
    done < $CC_FOLDERS

    find $folder_list \( -name '*.c' -o -name '*.cpp' -o -name '*.h' \) > ${CC_FILELIST}
    cmd_line="$cmd_line --file-list=${CC_FILELIST}"
else
    echo "ERROR: no method provided to search files to check."
    exit 66
fi

if [[ -f $CC_SUPRESS ]]; then
    cmd_line="$cmd_line --suppressions-list=${CC_SUPRESS}"
fi

# run cppcheck command
$cmd_line
ERR=$?

cppcheck-htmlreport --file=${CC_RESULT} --source-encoding="iso8859-1" --report-dir=${CC_FOLDER}
exit ${ERR}
